<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use PHPExcel;
class Withdraw extends BaseModel
{
    public $timestamps = false;

    protected $table = 'withdraw';

    protected $guarded = [];



    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getAllList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->with('user')->with('card')->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->with('user')->with('card')->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    /**
     * 人民币支出
     */
    public function withdraw_money_count()
    {
        $withdraw_money_count = Withdraw::where('status','2')->sum("money");
        return $withdraw_money_count;
    }


    /**
     * 提现单数
     */
    public function get_withdraw_count()
    {
        $withdraw_count = Withdraw::where('status','2')->count();
        return $withdraw_count;
    }
    
    /**
     * 表格导出
     */
    public function payExcel($request)
    {
        $add_time = $request['add_time'];
        $end_time= $request['end_time'];
        $add_time = empty($add_time)? 0:strtotime($add_time);
        $end_time=empty($end_time)? 0:strtotime($end_time);
//        $withdraw = M('withdraw');
//        $list = $withdraw
//            ->table('__WITHDRAW__ w')
//            ->field('
//				w.withdraw_id,
//				b.cardname,
//				w.uid,
//				b.bankname,
//				b.cardnum,
//				a.area_name aarea_name,
//				ab.area_name barea_name,
//				b.bank_branch,
//				w.all_money,
//				w.withdraw_fee,
//				w.money,
//				w.order_num,
//				w.add_time,
//				w.status')
//            ->join('__BANK__ b ON w.bank_id=b.id', 'LEFT')
//            ->join('__AREAS__ ab ON ab.area_id=b.address', 'LEFT')
//            ->join('__AREAS__ a ON a.area_id=ab.parent_id', 'LEFT')
//            ->join('__MEMBER__ m ON m.member_id=w.uid', 'LEFT')
//            ->where('w.add_time >'.$add_time)
//            ->select();
        $list = DB::table('withdraw')
            ->leftJoin('bank','withdraw.bank_id','=','bank.id')
            ->leftJoin('areas','bank.address','=','areas.area_id')
//            ->leftJoin(DB::raw('(areas) as ab'),'bank.address','=','ab.area_id')
//            ->leftJoin(DB::raw('(areas) as a'),'ab.parent_id','=','a.area_id')
            ->leftJoin('member','withdraw.uid','=','member_id')
//            ->where('areas.area_id','areas.parent_id')
            ->where('withdraw.add_time','<',$end_time)
            ->where('withdraw.add_time','>=',$add_time)
            ->select('withdraw.withdraw_id','bank.cardname','withdraw.uid','bank.bankname','bank.cardnum',DB::raw('(xnb_areas.area_name) as aarea_name,(xnb_areas.area_name) as barea_name'),'bank.bank_branch','withdraw.all_money','withdraw.withdraw_fee','withdraw.money','withdraw.order_num','withdraw.add_time','withdraw.status')
            ->get();
        foreach ($list as $k=>$v){
            $list[$k]->status = drawStatus($v->status);
            $list[$k]->add_time = date('Y-m-d H:i:s',$v->add_time);
            $list[$k]->cardnum = '`'.$v->cardnum.'`';
        }

        $re = Config::get();
        foreach ($re as $k=>$v) {
            $data[$v['key']] = $v['value'];
        }
        $filename= $data['name']."提现日志-".date('Y-m-d',time());
        $excel = new PHPExcel();
        //设置标题
        $excel->getActiveSheet()->setTitle($filename);
        //设置表头
        $excel->getActiveSheet()
            ->setCellValue('A1','Id')
            ->setCellValue('B1','提现人')
            ->setCellValue('C1','会员ID')
            ->setCellValue('D1','银行')
            ->setCellValue('E1','银行账号')
            ->setCellValue('F1','银行开户地')
            ->setCellValue('G1','银行开户地')
            ->setCellValue('H1','开户支行')
            ->setCellValue('I1','提现金额')
            ->setCellValue('J1','手续费')
            ->setCellValue('K1','实际金额')
            ->setCellValue('L1','订单号')
            ->setCellValue('M1','提交时间')
            ->setCellValue('N1','状态');

        //用foreach从第二行开始写数据，因为第一行是表头
        $i = 2;
        foreach($list as $val){
            $excel->getActiveSheet() ->setCellValue('A'.$i,$val->withdraw_id)
                ->setCellValue('B'.$i,$val->cardname )
                ->setCellValue('C'.$i,$val->uid)
                ->setCellValue('D'.$i,$val->bankname)
                ->setCellValue('E'.$i, $val->cardnum)
                ->setCellValue('F'.$i, $val->aarea_name)
                ->setCellValue('G'.$i, $val->barea_name)
                ->setCellValue('H'.$i, $val->bank_branch)
                ->setCellValue('I'.$i, $val->all_money)
                ->setCellValue('J'.$i, $val->withdraw_fee)
                ->setCellValue('K'.$i, $val->money)
                ->setCellValue('L'.$i, $val->order_num)
                ->setCellValue('M'.$i, $val->add_time)
                ->setCellValue('N'.$i, $val->status);
            $i++;
        }

        // 设置活动单指数到第一个表,所以Excel打开这是第一个表  
        $excel->setActiveSheetIndex(0);
        $obj_Writer = \PHPExcel_IOFactory::createWriter($excel,'Excel5');

        //设置header
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        //支持浏览器下载生成的文档 
        $all = $obj_Writer->save('php://output');//输出
        return $all;
    }

    /**
     * 提现审核 通过处理
     */
    public function success_by($request)
    {
        $withdraw_id = intval($request['withdraw_id']);
        //判断是否$id为空
        if (empty($withdraw_id)) {
            $res['status'] = 3;
            $res['msg'] = "参数错误!";
            return $res;
        }
        //查询用户可用金额等信息
        $info = $this->getMoneyByid($withdraw_id);
        if(!$info) {
            $res['status'] = -2;
            $res['msg'] = "系统繁忙,请稍后再试!";
            return $res;
        }
        if($info->status !== 3){
            $res['status'] = -1;
            $res['msg'] = "请不要重复操作!";
            return $res;
        }
        //通过状态为2
        $data ['status'] = 2;
        $data ['check_time'] = time();
        $data ['admin_uid'] = Session('admin_userid');
        $where['withdraw_id'] = $withdraw_id;
        //更新数据库
        $re = $this->up($where,$data);
        $num = Withdraw::where('withdraw_id',$withdraw_id)->first();
        //钱数减少
        $member = Member::where('member_id',$num['uid'])->first();
        $forzen_rmb = $member['forzen_rmb'];
        $money = $forzen_rmb-$num['all_money'];
        DB::table('member')->where('member_id',$num['uid'])->update(['forzen_rmb'=>$money]);
        if($re == false){
            $res['status'] = 0;
            $res['info'] = "提现操作失败!";
            return $res;
        }
        DB::table('message_all')->insert(['title'=>'CNY提现成功','u_id' => $info->member_id,'type'=> -2,'content' => '恭喜您提现'.$info->all_money.'成功！']);
        DB::table('finance')->insert(['member_id' => $info->member_id,'type' => 23,'content' => '提现'.$info->all_money,'money'=>$info->all_money-$info->withdraw_fee,'money_type' => 2,'currency_id' =>0]);
        $res['status'] = 1;
        $res['msg'] = "提现通过，操作成功!";
        return $res;
    }

    public function error_by($request)
    {
        $withdraw_id = intval($request['withdraw_id']);
        //判断是否$id为空
        if (empty($withdraw_id)) {
            $res['status'] = 3;
            $res['msg'] = "参数错误!";
            return $res;
        }
        //查询用户可用金额等信息
        $info = $this->getMoneyByid($withdraw_id);
        if(!$info) {
            $res['status'] = -2;
            $res['msg'] = "系统繁忙,请稍后再试!";
            return $res;
        }
        if($info->status !== 3){
            $res['status'] = -1;
            $res['msg'] = "请不要重复操作!";
            return $res;
        }
        //将提现的钱加回可用金额
        $money['rmb'] = floatval($info->rmb) + floatval($info->all_money);
        //将冻结的钱减掉
        $money['forzen_rmb'] = floatval($info->forzen_rmb) - floatval($info->all_money);

        //不通过状态为1
        $data ['status'] = 1;
        $data ['check_time'] = time();
        $data ['admin_uid'] = Session('admin_userid');
        $where['withdraw_id'] = $withdraw_id;
        //更新数据库,member修改金额
        $result = DB::table('member')->where('member_id',$info->member_id)->update($money);
        //withdraw修改状态
        $re = $this->up($where,$data);
        if($result == false){
            $res['status'] = 0;
            $res['msg'] = "提现不通过，操作失败!";
           return $res;
        }
        if($re == false){
            $res['status'] = 2;
            $res['msg'] = "提现不通过，操作失败!";
            return $res;
        }
        DB::table('message_all')->insert(['title'=>'CNY提现失败','u_id' => $info->member_id,'type'=> -2,'content' =>'很抱歉您提现失败，请重新操作或联系客服']);
        $res['status'] = 1;
        $res['msg'] = "提现不通过，操作成功!";
        return $res;
    }

    /**
     * 获取提现金额信息
     * @param unknown $id
     * @return boolean|unknown $rmb 会员号，可用金额，冻结金额，手续费，提现金额
     */
    public function getMoneyByid($id){

        $all = DB::table('withdraw')
            ->join('member','withdraw.uid','=','member.member_id')
            ->where('withdraw_id',$id)
            ->select('member.member_id','member.rmb','member.forzen_rmb','withdraw.status','withdraw.all_money','withdraw.withdraw_fee')
            ->first();
        if(empty($all)){
            return false;
        }
        return $all;
    }

    public function bank()
    {
        return $this->hasOne('App\Models\Bank', 'id', 'bank_id');
    }

    public function getWithdrawWithBank()
    {
        $where['uid'] = session('USER_KEY_ID');
        $order['add_time'] = 'desc';
        return $this->multiSelect('withdraw_id,all_money,money,add_time,bank_id,status')->with('bank')->withCertain('bank',['cardnum'])->multiWhere($where)->multiOrder($order)->take(10)->get()->toArray();
    }






}
